<template>
  <form class="validate-form-container">
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang="ts" setup>
import { onUnmounted } from "vue";
import { emitter } from "@/util/util";

// 定义触发的事件
const emits = defineEmits(["form-submit"]);
// 提交事件
const submitForm = () => {
  const result = funcArr.map((func) => func()).every((bool) => bool);
  emits("form-submit", result);
};

type ValidateFunc = () => boolean;
const funcArr: ValidateFunc[] = [];

// emitter监听的回调函数
const callback = (func: ValidateFunc) => {
  funcArr.push(func);
};

// 监听器
emitter.on("form-item-created", callback);
// 卸载页面时删除监听器
onUnmounted(() => {
  emitter.off("form-item-created");
  // 清空数组
  funcArr.length = 0;
  //   funcArr.splice(0);
});
</script>

<style scoped></style>
